<?php
/**
 * @author Amissah Gideon<kuulmek@yahoo.com>
 * @access public
 * @version 1.0
 */

class ProformaController extends AppController
{
    # Controller Name to be used
    var $name = 'Proforma';

    # Models to be used
    var $uses = array(
        'Proforma',
        'ProformaItem',
        'Customer',
        'Item',
        'Country',
        'Region',
        'User'
    );

    # set the layout to use
    var $layout = 'proforma_layout';

    # set the name of this module
    var $moduleName = 'Proforma';

    # Check the authenticity of the user
    function  beforeFilter()
    {
        parent::beforeFilter($this->moduleName);
        parent::setUpGlobalConfig();
    }

    # Controller actions
    /**
     * This function displays all the users in the system
     * @name index
     * @param void
     * @return Array of data.
     * @access public
     */
    function index(){
        $all_customers = $this->Customer->find('list', array(
            'fields'=>array('Customer.id','Customer.name'),
            'condition' => array('delete' => 'n'),
            'recursive' => -1
        ));
        $all_customers[0] = 'Select Customer';
        foreach($all_customers as $key => $value){
            $all_customers[$key] = strtoupper($value);
        }

        $all_items = $this->Item->find('list', array(
            'fields'=>array('Item.id','Item.name'),
            'condition' => array('delete' => 'n'),
            'recursive' => -1
        ));
        $all_items[0] = 'Select Items to add';
        foreach($all_items as $key => $value){
            $all_items[$key] = strtoupper($value);
        }

        $customer_types_opt = $this->customer_types;
        $country_list = $this->Country->find('list', array(
            'fields' => array('Country.id', 'Country.name'),
            'recursive' => -1
        ));

        $region_list = $this->Region->find('list', array(
            'fields' => array('Region.id', 'Region.rname'),
            'recursive' => -1
        ));

        $page_title = 'Proforma Invoice';
        $this->set(compact('page_title','all_items', 'all_customers','customer_types_opt','country_list','region_list'));
    }


    function manage_proformas(){
        $page_title = 'Proforma Invoice';
        $this->set(compact('page_title'));
    }

    /**
     * This function add a new record to the database
     * @name add
     * @param void
     * @return Json data
     * @access public
     */
    function add(){
        # Get the user session data
        $loggedUser = $this->Auth->user();
        # check whether the HTTP Request is an ajax request
        if ($this->request->is('ajax')) {
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;
            # retrieve the model
            $model = ucfirst($_POST['model']);
            # Check the model
            switch ($model) {
                case 'Customer' :
                    $loggedUser_id = $loggedUser['id'];

                    if(isset($this->request->data['Customer']['date_of_commence'])){
                        $this->request->data['Customer']['date_of_commence'] = $this->covertDate($this->request->data['Customer']['date_of_commence'],'mysql');
                    }

                    $this->request->data['Customer']['name'] = strtoupper($this->request->data['Customer']['name']);
                    $this->request->data['Customer']['contact_person'] = strtoupper($this->request->data['Customer']['contact_person']);
                    $this->request->data['Customer']['address'] = strtoupper($this->request->data['Customer']['address']);
                    $this->request->data['Customer']['city'] = strtoupper($this->request->data['Customer']['city']);
                    $this->request->data['Customer']['physical_location'] = strtoupper($this->request->data['Customer']['physical_location']);
                    $this->request->data['Customer']['comments'] = strtoupper($this->request->data['Customer']['comments']);

                    /** New Customer*/
                    $this->request->data['Customer']['created_by'] = $loggedUser_id;
                    $this->Customer->create();
                    # save the data
                    if($this->Customer->save($this->request->data)){
                        $rdata=array(
                            'id'=>$this->Customer->id,
                            'name'=>$this->toTitleCase($this->request->data['Customer']['name'])
                        );
                        return json_encode(array('code' => 0, 'data'=>$rdata,'mesg' => __('Data Saved')));
                    }
                    else{
                        return json_encode(array('code' => 1, 'mesg' => $this->Customer->invalidFields()));
                    }
                break;

                case 'Proforma' :
                    $upt_id = isset($_POST['row_id']) ? $_POST['row_id'] : false;
                    $loggedUser_id = $loggedUser['id'];
                    $data = json_decode($_POST['data'], true);

                    $next_auto_number = $this->Proforma->getNextAutoIncrement();
                    $invoice_number = "YGLPFM" . date('Ymd') . $next_auto_number;
                    $data['Proforma']['invoice_number'] = $invoice_number;
                    if ($upt_id) {
                        /** Edit*/
                        $this->Proforma->id = $upt_id;
                        $data['Proforma']['modified_by'] = $loggedUser_id;
                    }
                    else {
                        /** New*/
                        $this->Proforma->create();
                        $data['Proforma']['created_by'] = $loggedUser_id;
                    }

                    # save the data
                    if ($this->Proforma->saveAll($data)) {
                        $rdata=array(
                            'id'=>$this->Proforma->id
                        );
                        return json_encode(array('code' => 0, 'data'=>$rdata,'mesg' => __('Data Saved')));
                    }
                    else {
                        return json_encode(array('code' => 1, 'mesg' => __("Data Can't be Saved")));
                    }
                break;
            }
        }
    }


    /**
     *
     * @param void
     * @return html
     * @access public
     */
    function load(){
        $this->autoRender = false;
        $this->autoLayout = false;

        /** Loading */
        $userData = $this->Proforma->find('first',array(
            'fields' => array('Proforma.id','Proforma.proforma_number','Proforma.customer_id','Proforma.sales_type','Proforma.created','Proforma.created_by'),
            'conditions'=>array('Proforma.id'=>$_POST['data-id']),
            'contains'=> array(
                'ProformaItem'=>array(
                    'fields' => array('ProformaItem.id','ProformaItem.proforma_id','ProformaItem.item_id','ProformaItem.quantity','ProformaItem.discount'),
                    'Item'=>array('fields' => array('Item.id','Item.name','Item.amount'))
                ),
                'Customer'=>array('fields' => array('Customer.id','Customer.name'))
            ),
            'recursive'=>2
        ));

        //$userData = $this->Proforma->find('first',array(
          //  'conditions'=>array('Proforma.id'=>$_POST['data-id'])
        //));
        $creator = $this->User->getUserById($userData['Proforma']['created_by']);
        $userData['User'] = $creator['User'];
        //$userData = $this->Item->getById($_POST['data-id']);

        if ($userData) {
            return json_encode(array('code' => 0, 'data' => $userData, 'mesg' => __('Data Found')));
        }
        else {
            return json_encode(array('code' => 1, 'data' => array(), 'mesg' => __('No Record Found')));
        }
    }


    #
    function delete_(){
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;

            $loggedUser =  $this->Auth->user();
            $loggedUser_id = $loggedUser['id'];

            $ids = $_POST['ids'];
            $modObj = ClassRegistry::init('Proforma');
            $result = $modObj->updateAll(
                array('Proforma.deleted' => "'y'",'Proforma.modified_by' => $loggedUser_id),
                array('Proforma.id' => $ids)
            );

            if ($result) {
                echo json_encode(array('code' => 0, 'mesg' => __('Selected Item(s) have been successfully deleted')));
            }
            else {
                echo json_encode(array('code' => 1, 'mesg' => __('Selected Item(s) cannot be deleted')));
            }
        }
    }


    /**
     * @name get
     * @param void
     * @return Json Data
     */
    function get(){
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        /**  Get posted data */
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        /** The current page */
        $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
        /** Sort column */
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
        /** Sort order */
        $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
        /** Search column */
        $search_query = isset($_POST['query']) ? $_POST['query'] : '';
        /** Search string */
        $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
        $limit = $rp;
        $start = ($page - 1) * $rp;
        $made_sale_pr = isset($_POST['made_sale_pr']) ? $_POST['made_sale_pr'] : null;

        $condition_array = array('Proforma.deleted' => 'n');
        if (!empty($search_query)) {
            if ($qtype == 'invoice_number') {
                $condition_array = array(
                    'Proforma.invoice_number' => $search_query,
                    'Proforma.deleted' => 'n'
                );
            }
            else {
                $condition_array = array(
                    "Proforma.$qtype LIKE" => $search_query . '%',
                    'Proforma.deleted' => 'n'
                );
            }
        }

        $contain = array(
            'Sale'=>array('fields' => array('Sale.id')),
            'ProformaItem'=>array(
                'fields' => array('ProformaItem.id','ProformaItem.item_id','ProformaItem.quantity','ProformaItem.discount'),
                'Item'=>array('fields' => array('Item.id','Item.name'))
            ),
            'Customer'=>array('fields' => array('Customer.id','Customer.name'))
        );

        if ($made_sale_pr != null) {
            $condition_array2 = array();
            if($made_sale_pr == 'all'){}
            elseif($made_sale_pr == 'made_sale'){
                $condition_array2['NOT'] = array('Sale.proforma_id' => NULL);
            }
            elseif($made_sale_pr == 'no_sale'){
                $condition_array2['Sale.proforma_id'] =  NULL;
            }

            $contain = array(
                'Sale'=>array(
                    'conditions'=>$condition_array2,
                    'fields' => array('Sale.id')
                ),
                'ProformaItem'=>array(
                    'fields' => array('ProformaItem.id','ProformaItem.item_id','ProformaItem.quantity','ProformaItem.discount'),
                    'Item'=>array('fields' => array('Item.id','Item.name'))
                ),
                'Customer'=>array('fields' => array('Customer.id','Customer.name'))
            );
        }

        //debug($conditions);

        //$fields = array('Item.id','Item.name','Item.currency','Item.amount','Item.interest','Item.comments');

        $users = $this->Proforma->find('all', array('conditions' => $condition_array, 'contain'=>$contain ,'order' => "Proforma.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 2));
        $usersCount = $this->Proforma->find('count', array('conditions' => $condition_array, 'recursive' => -1));

        $total_records = $usersCount;

        if ($users) {
            $return_arr = array();
            foreach ($users as $obj) {
                $creator = $this->User->getUserById($obj['Proforma']['created_by']);
                $sale_type = 'CREDIT';
                if($obj['Proforma']['sales_type'] == 'out_right_purchase'){
                    $sale_type = 'OUT RIGHT PURCHASE';
                }

                $made_sale = 'NO SALES';
                if(isset($obj['Sale']['id'])){
                    $made_sale = 'MADE SALE';
                }
                $return_arr[] = array(
                    'id' => $obj['Proforma']['id'],
                    'cell' => array(
                        $obj['Proforma']['id'],
                        date('Y-m-d',strtotime($obj['Proforma']['created'])),
                        $obj['Proforma']['invoice_number'],
                        $sale_type,
                        $obj['Customer']['name'],
                        $made_sale,
                        $creator['User']['first_name'].' '.$creator['User']['first_name'].' '.$creator['User']['first_name']
                    )
                );
            }
            return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
        }
        else {
            return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
        }

    }

    function print_proforma_invoice($id = null)
    {
        $this->layout = 'print_invoice_layout';

        $json_data = $this->Proforma->find('first', array(
            'conditions' => array('Proforma.id'=>$id),
            'contain' => array(
                'Customer',
                'ProformaItem'=>array(
                    'fields'=>array('ProformaItem.id','ProformaItem.quantity','ProformaItem.discount'),
                    'Item'=>array('fields'=>array('Item.name','Item.specs','Item.amount','Item.currency'))
                )
            ),
            'recursive' => 2
        ));

        $comp_acct_no  = $this->proforma_account_no;
        if($json_data['Proforma']['sales_type'] == 'credit'){
            $print_statement  = $this->proforma_credit_statement;
        }
        else{
            $print_statement  = $this->proforma_outright_statement;
        }
        $controller = $this;
        $print_title = "PROFORMA INVOICE";
        $this->set(compact('json_data','print_title','controller','comp_acct_no','print_statement'));
    }
}